package cn.schoolwow.quickdao.module.database.dml.existQuery.kit;

import cn.schoolwow.quickdao.module.database.dml.existQuery.service.GetInstanceCountFlow;
import cn.schoolwow.quickdao.module.database.dml.existQuery.service.GetInstancesCountFlow;
import cn.schoolwow.quickdao.module.database.parent.kit.DatabaseDAOImpl;
import cn.schoolwow.quickflow.QuickFlow;
import cn.schoolwow.quickflow.domain.FlowContext;

import java.util.Collection;

public class DatabaseManipulationExistQueryImpl extends DatabaseDAOImpl implements DatabaseManipulationExistQuery {

    public DatabaseManipulationExistQueryImpl(QuickFlow quickFlow) {
        super(quickFlow);
    }

    @Override
    public boolean exist(Object instance) {
        if (null == instance) {
            return false;
        }
        FlowContext flowContext = quickFlow.startFlow(new GetInstanceCountFlow())
                .putTemporaryData("instance", instance)
                .execute();
        Long count = (Long) flowContext.checkData("count");
        return count>0;
    }

    @Override
    public boolean existAny(Object... instances) {
        FlowContext flowContext = quickFlow.startFlow(new GetInstancesCountFlow())
                .putTemporaryData("instances", instances)
                .execute();
        Long count = (Long) flowContext.checkData("count");
        return count>0;
    }

    @Override
    public boolean existAll(Object... instances) {
        FlowContext flowContext = quickFlow.startFlow(new GetInstancesCountFlow())
                .putTemporaryData("instances", instances)
                .execute();
        Long count = (Long) flowContext.checkData("count");
        return count==instances.length;
    }

    @Override
    public boolean existAny(Collection instances) {
        return existAny(instances.toArray());
    }

    @Override
    public boolean existAll(Collection instances) {
        return existAll(instances.toArray());
    }

}
